import requests
import re
from lxml import etree
from urllib import request
from tools.filterTags import filter_tags
import json

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    # 'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    # 'Host': 'www.baidu.com',
    'Pragma': 'no-cache',
    # 'Referer': 'https://www.baidu.com/',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
}


def beautify_str(line):
    return line.replace('\n', '').replace('\r', '').replace('\t', '').replace('\u3000', '').replace('\xa0', '').strip()


def main(cname):
    try:
        url = "https://baike.baidu.com/search?word={}&pn=0&rn=0&enc=utf8".format(request.quote(cname))
        r1 = requests.get(url, headers=headers)
        response1 = etree.HTML(r1.text)
        url2 = response1.xpath('//dl[@class="search-list"]/dd[1]/a/@href')[0]
        if 'baike.baidu.com' not in url2:
            url2 = 'https://baike.baidu.com' + url2
    except Exception as e:
        print(e)
        url2 = "https://baike.baidu.com/item/%s" % cname
    print(url2)

    r2 = requests.get(url2, headers=headers)
    r2.encoding = 'utf-8'
    response2 = etree.HTML(r2.text)
    # print(r2.text)
    item = {}
    item["词语"] = cname
    item['词条名'] = response2.xpath('//h1/text()')[0]
    try:
        item["百科内容"] = filter_tags(etree.tostring(response2.xpath("//*[@class='main-content']")[0], encoding="utf-8", pretty_print=True, method="html").decode('utf-8'))
        item["百科内容"] = beautify_str(item["百科内容"])
        item["百科长度"] = len(''.join(response2.xpath("//*[@class='main-content']//text()")).strip(' '))
        item["百科标签"] = '|'.join(response2.xpath("//*[@class='taglist']/text()")).replace('\xa0', '').replace('\n', '').replace('\r', '')
        item["百科ID"] = re.findall('newLemmaIdEnc:"(.*?)"', r2.text)[0]
        item["百科浏览量"] = json.loads(requests.get("https://baike.baidu.com/api/lemmapv?id=%s&r=0.7726277587689401" % item["百科ID"], headers=headers).text)['pv']
        item["目录"] = '|'.join(re.findall('(\d+\.\d+\\n.*?|\d+\\n.*?)\\n', ''.join(response2.xpath('//dl[@class="catalog-list"]//a[@class="title-link"]//text()')))).replace('\n', '')
    except Exception as e:
        print(e)
        item["百科内容"] = '未收录'
        item["百科长度"] = -1
        item["百科标签"] = ''
        item["百科ID"] = -1
        item["百科浏览量"] = -1
        item["目录"] = ''
    print(item)
    return item


if __name__ == "__main__":
    item = main('python')
